/**
 *
 */
package cn.hg.jfsa.core.handler;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.handler.Handler;
import com.jfinal.kit.HandlerKit;
import com.jfinal.kit.StrKit;

/**
 * 伪静态处理Handler
 *
 * @author Golly
 */
public class JfsaFakeStaticHandler extends Handler {

	private List<String> excludeViewPostfixList = new ArrayList<>();
	private String viewPostfix;

	public JfsaFakeStaticHandler () {
		this.viewPostfix = ".html";
	}

	/**
	 * @param viewPostfix
	 * @param excludeViewPostfixs
	 */
	public JfsaFakeStaticHandler (String viewPostfix, String... excludeViewPostfixs) {

		if (StrKit.isBlank(viewPostfix)) {
			throw new IllegalArgumentException("viewPostfix can not be blank.");
		}

		this.viewPostfix = viewPostfix;

		for (String prefix : excludeViewPostfixs) {
			this.excludeViewPostfixList.add(prefix);
		}

	}

	/*
	 * (non-Javadoc)
	 * @see com.jfinal.handler.Handler#handle(java.lang.String,
	 * javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse, boolean[])
	 */
	@Override
	public void handle (String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {

		if ("/".equals(target)) {
			this.next.handle(target, request, response, isHandled);
			return;
		}

		if (!this.isExclude(target)) { // 如果URL前缀不在排除前缀列表范围内，则启用伪静态

			if (target.indexOf('.') == -1) {
				HandlerKit.renderError404(request, response, isHandled);
				return;
			}

			int index = target.lastIndexOf(this.viewPostfix);

			if (index != -1) {
				target = target.substring(0, index);
			}

		}

		this.next.handle(target, request, response, isHandled);
	}

	/**
	 * 判断当前Action URL是否在排除前缀以内
	 *
	 * @param actionKey
	 *            Action Key
	 *
	 * @return true表示存在于排除表中
	 */
	private boolean isExclude (String actionKey) {

		for (String prefix : this.excludeViewPostfixList) {

			if (actionKey.startsWith(prefix)) {
				return true;
			}

		}

		return false;
	}

}
